package ex2a.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;

import ex2a.controller.Controller;

public class SemaphoresPanel extends JPanel {
	private static final long serialVersionUID = 1L;

	private Controller controller = null;
	private Dimension d;
	private Rectangle2D.Double semaphoreRect;
	private static final Color[] cores =
		{
			new Color(0xff0000), //Semaforo 0
			new Color(0x00ff00), //Semaforo 1
			new Color(0x0000ff), //Semaforo 2
		};
	
	public SemaphoresPanel() {
		controller = Controller.getInstance();
		controller.setSemaphoresPanel( this );
		d = new Dimension();
		semaphoreRect = new Rectangle2D.Double();
		
		setBackground( Color.WHITE );
		setForeground( Color.BLACK );
		
	}
	
	@Override
	public void paintComponent( Graphics _g ) {
		Graphics2D g = (Graphics2D) _g;
		int[] semaphores = controller.getSemaphores();
		double width, height;
		double paddingWidth, paddingHeight;
		int i = 0;

		d = getSize( d );
		
		width = d.getWidth();
		height = d.getHeight();
		
		g.setColor( getBackground() );
		g.fill( new Rectangle2D.Double( 0d, 0d, width, height ) );
		g.setColor( getForeground() );
		
		paddingHeight = height / 2;
		paddingWidth = 0.1 * ( width / (double) ( semaphores.length + 1 ) );
		
		semaphoreRect.width = 0.9 * ( width / (double) semaphores.length );
		semaphoreRect.height = paddingHeight;
		semaphoreRect.y = paddingHeight * 0.5;
		
		g.setFont( new Font("Comic Sans", Font.BOLD, (int) ( semaphoreRect.height * 0.75 ) ) );
		
		for( i = 0; i < semaphores.length; ++i ) {
			semaphoreRect.x = ( i * semaphoreRect.width + ( i + 1 ) * paddingWidth );
			
			g.setColor( cores[ i ] );
			g.fill( semaphoreRect );
			
			g.setColor( Color.BLACK );
			
			g.drawString( Integer.toString( semaphores[ i ] ), (float) semaphoreRect.getCenterX(), (float) ( semaphoreRect.getCenterY() + semaphoreRect.height / 4 ) );
			
		}
	}
	
}
